import {defineStore} from "pinia";

import {loginApi, logoutApi} from "@/api/auth";
import {getUserInfo} from "@/api/user";
import {resetRouter} from "@/router";
import {store} from "@/store";

import {LoginData} from "@/api/auth/types";

import {useStorage} from "@vueuse/core";

export const useUserStore = defineStore("user", () => {
	// state
	const userId = ref();
	const token = useStorage("accessToken", "");
	const name = ref("");
	const avatar = ref("");
	const perms = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
	const company = ref<Array<number>>([]); // 用户所属公司集合
	const department = ref<Array<number>>([]); // 用户所属部门集合

	/**
	 * 登录调用
	 *
	 * @param {LoginData}
	 * @returns
	 */
	function login(loginData: LoginData) {
		return new Promise<void>((resolve, reject) => {
			loginApi(loginData)
				.then((response) => {
					const {tokenType, accessToken} = response.data;

					token.value = tokenType + " " + accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
					resolve();
				})
				.catch((error) => {
					reject(error);
				});
		});
	}

	// 获取信息(用户昵称、头像、角色集合、权限集合)
	function getInfo() {
		return new Promise((resolve, reject) => {
			getUserInfo()
				.then(({data}) => {
					if (!data) {
						return reject("Verification failed, please Login again.");
					}

					userId.value = data.uid;
					name.value = data.name;
					avatar.value = data.avatar;
					company.value = data.company;
					department.value = data.department;
					perms.value = data.perms;
					resolve(data);
				})
				.catch((error) => {
					reject(error);
				});
		});
	}

	// 注销
	function logout() {
		return new Promise<void>((resolve, reject) => {
			logoutApi()
				.then(() => {
					resetRouter();
					resetToken();
					location.reload(); // 清空路由
					resolve();
				})
				.catch((error) => {
					reject(error);
				});
		});
	}

	// 重置
	function resetToken() {
		token.value = "";
		name.value = "";
		avatar.value = "";
		perms.value = [];
		company.value = [];
		department.value = [];
	}

	return {
		token,
		name,
		avatar,
		perms,
		login,
		getInfo,
		logout,
		resetToken,
		/**
		 * 当前登录用户ID
		 */
		userId,
		company,
		department,
	};
});

// 非setup
export function useUserStoreHook() {
	return useUserStore(store);
}
